#!/usr/bin/env bash
APP_NAME=nimble-eureka-server
APP_HOME=$(dirname $(pwd))/${APP_NAME}
PID_FILE=${APP_HOME}/pid
LOG_FILE=${APP_HOME}/logs/console.out
JAVA_OPTS=-Xms512m
BOOST_JAR=nimble-eureka-server.jar
PARAMS='-Dinstance.host=127.0.0.1 -Devn'


mkdir -p ${APP_HOME}/logs

#
if [ ! -f "$PID_FILE" ]; then
  touch "$PID_FILE"
  echo 0 > ${PID_FILE}
fi
pid=0


#=========================
getpid(){
  pid=`cat ${PID_FILE}`
}
#==========================
run()
{
    if [ ${pid} -ne 0 ]; then
        echo "================================"
	echo "already started!"
	echo "================================"
	exit 1
    fi
    java -server ${JAVA_OPTS} ${PARAMS} -jar ${BOOST_JAR}
}
#==========================
start()
{
    getpid
    nohup java -server ${JAVA_OPTS}  ${PARAMS} -jar ${BOOST_JAR} >> ${LOG_FILE} 2>&1 & echo $! > ${PID_FILE}
    echo "Starting..."
    getpid
    if [ ${pid} -ne 0 ]; then
      echo "================================"
      echo "[Start Success] (pid=$pid)" 
      echo "================================" 
    else 
      echo "================================"
      echo "[Start Failed]"
      echo "================================"
    fi
}
#==========================
stop()
{
  getpid
  echo "killing ${pid}"
  if [ ${pid} -ne 0 ]; then
    skill -15 ${pid}
    echo "================================"
    echo "stoping"
    echo "================================"
    echo 0 > ${PID_FILE}
  fi
}
#==========================
case "$1" in
  'run')
      run
      ;;
  'start') 
      start 
      ;; 
  'stop') 
      stop
      ;; 
  *) 
      echo "Usage: $0 {run|start|stop}" 
      exit 1 
esac

exit 0